package com.jk.quartz;

import com.jk.util.DateUtil;
import com.jk.util.quartz.TriggerMethod;
import org.apache.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.support.RequestContext;

import java.io.File;
import java.util.Date;

/**
 * Created by yanghuan on 2015/12/30.
 */
@Service
public class DeleteFileJob {
    private static final Logger logger = Logger.getLogger(DeleteFileJob.class);

    @TriggerMethod
    public void execute(String data) {
        logger.error("进入定时任务");
        try {
            //获取根目录，无需ServletContext环境
            String root = RequestContext.class.getResource("/").getFile();
            //File.separatorChar 获取window系统的"\"或者unix"/"
            String zipRoot = new File(root).getParentFile().getParentFile().getCanonicalPath() + File.separatorChar + "zipRoot";
            File zipRootFile = new File(zipRoot);
            File[] files = zipRootFile.listFiles();
            if (null != files) {
                for (int i = 0; i < files.length; i++) {
                    File file = files[i];
                    String fileName = file.getName().substring(0, file.getName().lastIndexOf("."));
                    String[] strs = fileName.split("_");
                    if (strs.length > 1) {
                        Long timestamp = Long.valueOf(strs[strs.length - 1]);
                        Date date = new Date(timestamp);
                        Date nowDate = new Date();
                        if (nowDate.after(DateUtil.addMinutes(date, 10))) {
                            file.delete();
                        }
                    } else {
                        file.delete();
                    }
                }
            }
            logger.error("定时任务完成");
        } catch (Exception e) {
            logger.error("定时任务失败", e);
        }
    }
}
